package edu.hit;

import edu.hit.RESP.BulkString;
import edu.hit.RESP.RespData;
import edu.hit.RESP.SimpleString;

public class CommandHandler {
    public CommandHandler(String commands) {
        this.commands = commands;
    }

    public enum Command{
        PING,ECHO
    }

    private String commands;

    public RespData response(){



        String[] commandArray = commands.split(" ");

        String command = commandArray[0].toLowerCase();






        return switch (command){
            case "ping" -> new SimpleString("PONG");
            //echo <msg>
            case "echo" -> new BulkString(commandArray[1]);
            //set <key> <value>(px <milliseconds>)
            case "set" -> {
                String key =null,value = null;
                if(commandArray.length == 3){

                    key = commandArray[1];
                    value = commandArray[2];
                    Storage.set(key,new Data(value,System.currentTimeMillis(),null));
                }else if(commandArray.length == 5 && commandArray[3].equalsIgnoreCase("px")){
                    Storage.set(key,new Data(commandArray[2],System.currentTimeMillis(),Long.parseLong(commandArray[4])));
                }

                yield new SimpleString("OK");
            }
            //get <key>
            case "get" -> {
                String key = commandArray[1];
                Data data = Storage.get(key);
                if(data != null && data.getExpiredIn() != null){
                    if(data.getExpiredIn() <= System.currentTimeMillis() - data.getCreatedAt()){
                        //data = null;
                        Storage.remove(key);
                        yield new BulkString(null);
                    }else yield new BulkString(data.getValue().toString());
                }else if(data != null && data.getExpiredIn() == null){
                    yield new BulkString(data.getValue().toString());
                }

                yield new BulkString(null);
            }
            //info (<section>)
            case "info" -> {
                if(commandArray.length == 2){
                    String section = commandArray[1];
                    yield new BulkString(Configuration.getInfo(section));
                }else if(commandArray.length == 1){
                    yield new BulkString(Configuration.getAllInfo());
                }
                yield null;
            }
            case "replconf" -> new SimpleString("OK");
            case "psync" -> new SimpleString("FULLRESYNC " + Configuration.getMaster_replid() + " " + Configuration.getMaster_repl_offset());

            default -> throw new IllegalStateException("Unexpected value: " + command);
        };
    }

}
